package com.ruoyi.extdata.component;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.service.IMonitorLogService;
import com.ruoyi.common.config.EmailConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.EmailUtils;
import com.ruoyi.common.utils.Func;
import com.ruoyi.common.vo.EmailVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Monnify工单
 *
 * @author cyh
 */
@Component
@Slf4j
@AllArgsConstructor
public class MonnifyOrder {

    private IMonitorLogService monitorLogService;

    private RedisCache redisCache;

    private static final String EXT_MONNIFY_ORDER_KEY = "ExternalOrder:monnifyOrder";

    public void submitOrder(String ex) {
        //检查1h内Monnify接口触发监控报警的次数
        int monitForAnHourCount = monitorLogService.getMonitForAnHourCount();
        if (monitForAnHourCount >= 3) {
            //检查2小时内是否有发送过工单
            Object order = redisCache.getCacheObject(EXT_MONNIFY_ORDER_KEY);
            log.info("检查2小时内是否有发送过工单:{}",order);
            //发送过 结束
            if (Func.isNotEmpty(order)) {
                return;
            }
            redisCache.setCacheObject(EXT_MONNIFY_ORDER_KEY, "1", 2, TimeUnit.HOURS);
            //发送邮件
            sendEmail(ex);
        }
    }

    private static void sendEmail(String ex) {
        StringBuilder content = new StringBuilder();
        content.append("<html><head></head><body>Dear Monnify,<br/>The interface is experiencing a large number of exceptions and timeouts. Please resolve the issue and provide feedback.<br/><br/><br/><br/>");
        content.append(ex);
        content.append("<br/><br/><br/><br/>Regards<br/>LinkCredit</body></html>");

        JSONObject jsonObject = new JSONObject();
        EmailVo emailVo = EmailVo.builder()
                .subject("Interface exception and timeout")
                .addressees(EmailConfig.getMonifyOrderAddress().split(","))
                .cc(EmailConfig.getMonifyOrderCc().split(","))
                .content(content.toString())
                .param(jsonObject)
                .build();
        EmailUtils.sendCustomizeEmail(emailVo);
    }


}
